<template>
	<view class="search-box">
		<!-- 使用 uni-ui 提供的搜索组件 -->
		<uni-search-bar @input="input" :radius="100" cancelButton="none" focus="auto"></uni-search-bar>
	</view>
	<!-- 搜索历史 -->
	<view class="history-box" v-if="searchResults.length == 0">
		<!-- 标题区域 -->
		<view class="history-title">
			<text>搜索历史</text>
			<uni-icons type="trash" size="17" @click="deletehistory"></uni-icons>
		</view>
		<!-- 列表区域 -->
		<view class="history-list">
			<uni-tag :text="item" v-for="(item, i) in historyList" :key="i" custom-style="margin: 0px 5px 0 0;"
				@click="gotogoodslist(item)"></uni-tag>
		</view>
	</view>
	<view class="sugg-list" v-else>
		<view class="sugg-item" v-for="(item, i) in searchResults" :key="item.goods_id" @click="gotoDetail(item.goods_id)">
			<view class="goods-name">{{item.goods_name}}</view>
			<uni-icons type="arrowright" size="16"></uni-icons>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from 'vue';
	const timer = ref(null)
	//搜索结果
	const searchResults = reactive([])
	const keyword = ref('')
	// 搜索关键词的历史记录
	const historyList = reactive(JSON.parse(uni.getStorageSync('keyword')) || [])
	//获取搜索关键词，并进行防抖操作
	const input = (e) => {
		// console.log(e);
		clearTimeout(timer.value)
		timer.value = setTimeout(() => {
			// console.log(e);
			keyword.value = e
			if (e !== '') {
				historyList.unshift(keyword.value)
				if (new Set(historyList).size !== historyList.length) {
					// 1. 将 Array 数组转化为 Set 对象
					const set = new Set(historyList)
					// 2. 调用 Set 对象的 delete 方法，移除对应的元素
					set.delete(keyword.value)
					// 4. 将 Set 对象转化为 Array 数组
					historyList.length = 0
					historyList.push(...Array.from(set))
					historyList.unshift(keyword.value)
				}
				// 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
				uni.setStorageSync('keyword', JSON.stringify(historyList))
				// console.log(JSON.parse(uni.getStorageSync('keyword')));
			}
			getsearchResults()
		}, 500)
	}
	//请求搜索建议列表
	const getsearchResults = async () => {
		if (keyword.value == '') {
			searchResults.length = 0
			return
		}
		const {
			data: res
		} = await uni.$http.get('/api/public/v1/goods/qsearch', {
			query: keyword.value
		})
		if (res.meta.status !== 200) {
			return uni.$showMsg()
		}
		searchResults.length = 0
		searchResults.push(...res.message)
		// console.log(searchResults);
	}
	//跳转详情页面并传递 goods_id 参数
	const gotoDetail = (id) => {
		uni.navigateTo({
			url: `/subpkg/goods_detail/goods_detail?goods_id=${id}`
		})
	}
	//清空搜索历史
	const deletehistory = () => {
		historyList.length = 0
		uni.removeStorageSync('keyword')
	}
	//跳转商品列表
	const gotogoodslist = (item) => {
		uni.navigateTo({
			url: `/subpkg/goods_list/goods_list?query=${item}`
		})
	}
</script>

<style lang="scss">
	:deep(.uni-searchbar) {
		background-color: #c00000;
	}

	.search-box {
		position: sticky;
		top: 0;
		z-index: 999;
	}

	.history-box {
		padding: 0 5px;

		.history-title {
			display: flex;
			justify-content: space-between;
			border-bottom: 1px solid #efefef;
			align-items: center;
			height: 40px;
			font-size: 13px;
		}

		.history-list {
			display: flex;
			flex-wrap: wrap;
			padding-top: 5px;
		}
	}

	.sugg-list {
		padding: 0 5px;

		.sugg-item {
			font-size: 12px;
			padding: 13px 0;
			border-bottom: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.goods-name {
				// 文字不允许换行（单行文本）
				white-space: nowrap;
				// 溢出部分隐藏
				overflow: hidden;
				// 文本溢出后，使用 ... 代替
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}
	}
</style>